<template>
	<gracePage headerBG="#F5F5F5" :bounding="false">
		<view slot="gHeader">
			<view class="grace-header-body grace-relative main-bodybg-color">
				<text class="grace-header-icons your-icon iconxiangzuo font-size-34" style="" @tap="navigateBackFn"></text>
				<!-- 中间内容 -->
				<view class="grace-header-content-noflex py-1-5 px-3 text-center"><text class="grace-h4 text-center font-size-36" style="font-size:36rpx;">确认订单</text></view>
				<!-- 消息按钮 -->
				<text class="grace-header-icons my-icons"></text>
			</view>
		</view>
		<view slot="gBody" class="grace-flex-v1 main-bodybg-color" id="gBody">
			<view class="grace-list-items grace-tbr-large mx-2 grace-bg-white mt-3" @click="selectSite">
				<template v-if="path">
					<view class="grace-list-body ml-0 pl-2">
						<view class="grace-list-title">
							<text class="grace-list-title-text grace-bold">{{ path.consignee }}</text>
						</view>
						<view class="grace-list-body-desc grace-bold">{{ path.province_name }}{{ path.city_name }}{{ path.district_name }}{{ path.address }}</view>
						<view class="grace-wrap">
							<view class="grace-list-body-desc font-size-26 grace-bold pr-1">电话：</view>
							<view class="grace-list-body-desc">{{ path.mobile }}</view>
						</view>
					</view>
				</template>
				<template v-else>
					<view class="grace-list-body ml-0 pl-2"><text class="grace-yellow">暂无默认收货地址请选择!</text></view>
				</template>
				<text class="grace-list-arrow-right grace-icons icon-arrow-right pr-2"></text>
			</view>

			<divider></divider>
			<view class="grace-tbr-large grace-bg-white mx-2">
				<view class="m-2">
					<view class="grace-space-between pt-1">
						<text class="grace-h5">臻选优品</text>
						<text class="grace-h5 grace-black9">正品保证</text>
					</view>
					<view class="grace-list my-2" v-for="(goods, indexItem) in getStateList" :key="indexItem">
						<view class="grace-list-items">
							<view class="my-list-image ucenter-face grace-relative">
								<image class="my-list-image ucenter-face-image" :src="goods.goods_img" mode="widthFix"></image>
							</view>
							<view class="grace-list-body">
								<view class="grace-list-title">
									<text class="my-list-title-text grace-h4 grace-ellipsis">{{ goods.goods_name }}</text>
								</view>
								<view class="grace-list-title py-1">
									<text class="my-list-title-text grace-black9 grace-text">{{ goods.selectText }}</text>
								</view>
								<view class="grace-space-between mt-1 grace-flex-vcenter">
									<text class="grace-h5 grace-red">￥{{ goods.product_price || goods.goods_price }}</text>
									<text class="font-size-22 pr-2">x{{ goods.goods_number }}</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<divider></divider>
			<view class="py-2 grace-tbr-large grace-bg-white mx-2">
				<view class="mx-2">
					<radio-group name="danxuan" color="#1CA376">
						<view class="grace-form-item" v-for="(item, index) in payLists" :key="index">
							<view class="grace-flex grace-flex-vcenter">
								<image :src="item.icon" style="width: 46rpx;height: 46rpx;"></image>
								<text class="grace-form-label grace-black  ml-2">{{ item.text }}</text>
							</view>
							<view class="grace-form-body" style="padding:20rpx 0;text-align: right;">
								<label class="grace-check-item-v"><radio :value="item.value" :checked="index === current" @click="changePay(index)"></radio></label>
							</view>
						</view>
					</radio-group>
				</view>
			</view>
			<divider></divider>
			<view class="py-2 grace-tbr-large grace-bg-white mx-2">
				<view class="mx-2">
					<view class="grace-space-between pt-1">
						<text class="grace-h5">商品金额</text>
						<text class="grace-h5 grace-black9">￥{{ getStateList[0].product_price || shopPrice }}</text>
					</view>
					<view class="grace-space-between pt-1">
						<text class="grace-h5">优惠金额</text>
						<text class="grace-h5 grace-black9">￥{{ coupon }}</text>
					</view>
					<view class="grace-space-between pt-1">
						<text class="grace-h5">运费</text>
						<text class="grace-h5 grace-black9">￥{{ freightNum }}</text>
					</view>
				</view>
			</view>
			<divider></divider>
			<view class="py-2 grace-bg-white mb-5" v-if="switchShow">
				<view class="mx-3">
					<text>使用礼包兑换</text>
					<view class="grace-list-items">
						<view class="grace-flex grace-flex-vcenter"><image src="/static/images/lihe.png" style="width: 92rpx;height: 92rpx;"></image></view>
						<view class="grace-list-body">
							<view class="grace-list-title"><text class="grace-list-title-text">臻之筱会员礼包</text></view>
							<text class="grace-list-title-text grace-black9">x {{ userInfo.club_card }}</text>
						</view>
						<!-- <text class="grace-list-arrow-right grace-icons icon-arrow-right"></text> -->
						<switch checked="switchChe" @change="switch1Change" color="#1CA376" style="transform:scale(0.7)" />
					</view>
				</view>
			</view>
			<graceHeaderAlert ref="graceHeaderAlert2" background="#FF0036" :width="500"><text class="grace-h5 grace-white">X 地址信息错误</text></graceHeaderAlert>
		</view>
		<!-- 底部导航 -->
		<view class="grace-footer grace-space-between" slot="gFooter">
			<view class="grace-grids" style="width:250rpx;">
				<view class="grace-wrap grace-flex-vcenter ml-3">
					<text class="">合计：</text>
					<text class="grace-h4 grace-red">￥ {{ totalPrice }}</text>
				</view>
			</view>
			<view class="grace-flex-end" style="width:460rpx;">
				<button type="primary" class="grace-button my-footer-button grace-white  mr-2 my-1 grace-tbr-large" @tap="gotoPay" :loading="submitPay" :disabled="submitPay">
					支付
				</button>
			</view>
		</view>
	</gracePage>
</template>
<script>
import gracePage from '@/graceUI/components/gracePage.vue';
import graceHeaderAlert from '@/graceUI/components/graceHeaderAlert.vue';
import tools from '@/common/js/tools.js';
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex';
export default {
	data() {
		return {
			// payLists: [],
			path: false,
			current: 0,
			// 避免重复提交
			submitPay: false,
			// 商品列表
			getStateList: [],
			freightNum: '0.00',
			// 优惠金额
			coupon: '0.00',
			// 商品金额
			shopPrice: 0,
			// 是否使用礼包
			switchChe: true,
			switchShow: false,
			// 合计
			totalPrice: 0,
			oldTotalPrice: '',
			// 阻止表单多次提交
			preventStatus: true
		};
	},
	computed: {
		...mapState({
			userInfo: state => state.user.userInfo
		}),
		...mapGetters(['defaultPath']),
		payLists() {
			let arr = [];
			// #ifdef APP-PLUS
			arr.push({
				text: '微信',
				icon: 'https://img-cdn-qiniu.dcloud.net.cn/uni-ui/grid-2.png',
				name: 'wechat_app',
				provider: 'wxpay'
			});
			arr.push({
				text: '支付宝',
				icon: 'https://img-cdn-qiniu.dcloud.net.cn/uni-ui/grid-8.png',
				name: 'alipay',
				provider: 'alipay'
			});
			// #endif
			// #ifdef MP
			arr.push({
				text: '微信',
				icon: 'https://img-cdn-qiniu.dcloud.net.cn/uni-ui/grid-2.png',
				name: 'miniapp',
				provider: 'wxpay'
			});
			// #endif
			return arr;
		}
	},
	watch: {
		switchChe(newName, oldName) {
			if (newName) {
				this.libaoFn();
			} else {
				this.getFreightFn(this.getStateList);
				this.coupon = '0.00';
			}
		}
	},
	onShow() {
		// 开启监听选择收货地址事件
		uni.$on('choosePath', res => {
			this.path = res;
			// 清除监听
			uni.$off('choosePath');
		});
	},
	onLoad(e) {
		if (e) {
			var goods = decodeURIComponent(e.goods);
			this.getStateList = JSON.parse(goods);
			this.getFreightFn(this.getStateList);
		}
		// 得到默认的地址
		if (this.defaultPath.length != 0) {
			this.path = this.defaultPath[0];
		} else {
			this.addressListFn();
		}

		// 判断当前用户可以是否使用礼包
		if (this.getStateList[0].is_suit == 1) {
			this.switchShow = true;
			this.libaoFn();
		}
	},
	methods: {
		...mapMutations(['getList']),
		...mapActions(['getUserInfo']),
		// 回退事件
		navigateBackFn: function() {
			uni.navigateBack();
		},
		buyNumChange() {
			console.log('aasds');
		},
		// 修改地址
		selectSite() {
			// 整合
			this.navigateTo({
				url: '/pages/homeBox/addressList/addressList?type=choose'
			});
		},
		getFreightFn(arr) {
			let total = 0;
			for (var i = 0; i < arr.length; i++) {
				console.log('arr[i]', arr[i]);
				total = tools.accAdd(total, tools.accMul(+(arr[i].goods_price || arr[i].goods_price), parseInt(arr[i].goods_number)));
			}
			// 商品金额
			this.oldTotalPrice = total;
			// 套装商品不参与折扣优惠
			console.log('this.getStateList[0].is_suit', this.getStateList[0].is_suit);
			if (this.getStateList[0].is_suit === 1) {
				let copyTotal = total;
				if (parseFloat(total) <= 99) this.freightNum = 10;
				this.totalPrice = tools.accAdd(total, this.freightNum);
				// 判断当前进来的商品是不是套装 是需要优惠价
				console.log(copyTotal);
				console.log(this.totalPrice, this.freightNum);
				this.shopPrice = copyTotal;
			} else {
				// 正常单个商品
				// 计算折扣价
				let copyTotal = total;
				total = tools.accMul(total, +this.userInfo.discount);
				if (parseFloat(total) <= 99) this.freightNum = 10;
				this.totalPrice = tools.accAdd(total, this.freightNum);
			}
		},
		async addressListFn() {
			let data = await this.$HTTP.post('/api/api.php', { act: 'get_address' }, { token: true });
			console.log('addressListFn', data);
			// 存储地址
			this.getList(data.address);
			if (this.defaultPath.length) {
				this.path = this.defaultPath[0];
			}
		},
		// 监听选中的支付方式
		changePay(e) {
			this.current = e;
		},
		async gotoPay() {
			this.submitPay = true;
			// 获取支付方式和地址信息
			let payMethod = this.payLists[this.current],
				pathMethod = this.path;
			if (!pathMethod) {
				// 请先选择地址
				this.$refs.graceHeaderAlert2.open();
				this.submitPay = false;
				return;
			}

			let options = {
				act: 'add_order',
				pay_type: payMethod.name,
				address_id: pathMethod.address_id,
				goods: this.getStateList
			};
			// 判断是否套装 并使用礼包
			if (this.switchShow && this.switchChe) options.is_suit = 1;

			let data = await this.$HTTP.post('/api/api.php', options, { token: true });

			// #ifdef MP-WEIXIN || MP-QQ
			uni.requestPayment({
				timeStamp: data.timeStamp,
				nonceStr: data.nonceStr,
				package: data.package,
				signType: 'MD5',
				paySign: data.paySign,
				success: res => {
					uni.showToast({ title: '支付成功', icon: 'none', mask: true });
					// 为避免二次支付 需要重新获取 用户的0元购条件
					this.getUserInfo();
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/order/orderList/orderList?index=2'
						});
					
					}, 1500);
				},
				fail: res => {
					uni.showToast({ title: '支付失败', icon: 'none', mask: true });
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/order/orderList/orderList?index=1'
						});
					}, 1500);
				},
				complete: () => {}
			});
			// #endif
			// #ifdef APP-PLUS
			// 判断是支付宝支付还是微信支付
			if (payMethod.provider === 'wxpay') data = data.info;
			uni.requestPayment({
				provider: payMethod.provider,
				orderInfo: data,
				success: e => {
					uni.showToast({ title: '支付成功', icon: 'none', mask: true });
					// 为避免二次支付 需要重新获取 用户的0元购条件
					this.getUserInfo();
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/order/orderList/orderList?index=2'
						});
					}, 1500);
				},
				fail: e => {
					console.log(e);
					uni.showToast({ title: '支付失败', icon: 'none', mask: true });
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/order/orderList/orderList?index=1'
						});
					}, 1500);
				},
				complete: () => {
					this.submitPay = false;
				}
			});
			// #endif
		},
		switch1Change() {
			this.switchChe = !this.switchChe;
		},
		libaoFn() {
			let libao = +this.userInfo.club_card,
				goodsNumber = this.getStateList[0].goods_number;
			if (libao == 0) return;
			let num = goodsNumber > libao ? libao : goodsNumber;
			console.log('num', num);
			this.totalPrice = tools.accMul(+num, 58);
			this.coupon = tools.accSub(this.shopPrice, tools.accSub(this.totalPrice, this.freightNum));
		}
	},
	components: { gracePage, graceHeaderAlert }
};
</script>
<style scoped>
.my-list-image {
	width: 154rpx;
	height: 154rpx;
}
.my-footer-button {
	width: 210rpx;
	height: 80rpx;
	line-height: 80rpx;
	font-size: 30rpx;
	text-align: center;
}
.my-list-title-text {
	display: block;
	line-height: 40rpx;
}
</style>
